package juc.cas;

import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.atomic.AtomicStampedReference;

/*
* ABA 问题 在compareAndSet过程中并并不能察觉值有没有被修改 只能察觉值有没有变化
* 解决:AtomicStampedReference
* */
public class Test8 {
    static AtomicStampedReference<Integer> integerAtomicReference=new AtomicStampedReference<>(18,0);
    public static void main(String[] args) throws InterruptedException {

        Integer pre = integerAtomicReference.getReference();
        int prestamp = integerAtomicReference.getStamp();
        other();
        Thread.sleep(1000);
        System.out.println(integerAtomicReference.compareAndSet(pre,1818,prestamp,prestamp+1));
        System.out.println(integerAtomicReference.getReference());
    }
    private static void other(){
        new Thread(()->{
            Integer pre = integerAtomicReference.getReference();
            int prestamp = integerAtomicReference.getStamp();
            System.out.println(Thread.currentThread().getName()+"->"+integerAtomicReference.compareAndSet(pre, 1919,prestamp,prestamp+1));
        },"t1").start();
        try {
            Thread.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        new Thread(()->{
            Integer pre = integerAtomicReference.getReference();
            int prestamp = integerAtomicReference.getStamp();
            System.out.println(Thread.currentThread().getName()+"->"+integerAtomicReference.compareAndSet(pre, 18,prestamp,prestamp+1));
        },"t2").start();
    }
}
